<template>
  <div class="myactivities">
    <div class="square_header flex align_center">
      <div class="square_header_item" :class="form.get_type == index ? 'underline ' : ''" v-for="(item, index) in activity"
        style="width:120px;" :key="index" @click="checkItem(index)">
        <span :class="form.get_type == index ? 'title1 color1 zIndex fontBold ' : 'default'">{{ item.name }}</span>
      </div>
    </div>
    <div class="myactivitiesBox">
      <van-pull-refresh v-model="refreshing" disabled @refresh="onRefresh" class="refresh-content">
        <van-list class="content-list" v-model="loading" :finished="finished" @load="loadMore" :immediate-check="false">
          <div class="college_list" v-for="(item, index) in demandList" :key="index" @click="goActivity(item.id)">
            <div class="college_list_box">
              <div>
                <img class="college_img" :src="item.tpic">
              </div>
              <div class="college_info">
                <p class="college_list_box_p van-multi-ellipsis--l2 color1 fontBold content1"
                  v-if="item.active_suatus === 1">
                  <van-tag style="height:18px;width:55px;justify-content: center;" class="tagleft" color="#FF7A1F"
                    type="primary">
                    报名中
                  </van-tag>
                  {{ item.title }}
                </p>
                <p class="college_list_box_p van-multi-ellipsis--l2 color1 fontBold content1"
                  v-if="item.active_suatus === 2 || item.active_suatus === 3">
                  <van-tag style="height:18px;width:55px;justify-content: center;" class="tagleft" color="#999999"
                    type="primary">
                    {{ item.active_suatus === 2 ? '已结束' : '已截止' }}
                  </van-tag>
                  {{ item.title }}
                </p>
                <div class="content2 font400 color6 " style="margin-top: 10px;">
                  <div class="activeInfo">{{form.get_type ? '报名人：' + item.sign_username : '参加人：' + item.join_username}}</div>
                  <div class="activeInfo">活动时间：{{item.active_start_time}}</div>
                  <div class="activeInfo">报名时间：{{item.sign_time}}</div>
                  <div v-if="item.order_id && !form.get_type">
                    <div @click.stop="downPdf(item.id,item.order_id)" class="copy font400 color4 content2">
                      下载回执
                    </div>
                  </div>
                  <!-- <span v-if="item.receipt_url">{{ item.deadline }}</span>
                  <span v-else>活动时间:{{ item.deadline }}</span> -->
                  <!-- <span class=" left12">限时免费</span> -->
                </div>
              </div>
            </div>
            <div class="confin flex align_center justify_between">
              <div v-if='!form.get_type' class="confinItem cancle font400 content2 color3" @click.stop="cancellation(item.sign_id, item.order_id)">
                取消报名
              </div>
              <div class="confinItem see font400 content2 color2" @click.stop="ActivityQrcode(item.id)">
                进活动群
              </div>
            </div>
          </div>
        </van-list>
      </van-pull-refresh>
    </div>
    <no-data v-if="demandList.length === 0" />
  </div>
  <div class="fexd_footer">
    <div class="footer_btn flex align_center justify_between">
      <div class="flex align_center">
        <div @click="back" class="agree font400 content3 color4">
          返回
        </div>
      </div>
    </div>
  </div>

  <van-dialog v-model:show="showQrCode" @confirm="closeQrCode" title="扫码进群" :close-on-click-overlay="false"
  confirm-button-color="#FF7A1F">
    <div class="Scan">
      <p class="font400 content3 color3">
        长按识别二维码，进入本期活动微信群
      </p>
      <img :src="qrCodeUrl">
    </div>
  </van-dialog>

  <van-dialog v-model:show="show" >
    <div class='noBox'>
      <div style="margin-bottom: 10px">本订单已支付，暂不支持取消。</div>
      <div style="margin-bottom: 10px">如欲取消报名,请联系平台活动客服:</div>
      <div class="phone1" style='font-size: 30px;font-weight: bold;'>
        <a :href="'tel:' + phone.mobile" ref="telPhone">{{phone.mobile}}</a>
      </div>
    </div>
  </van-dialog>
</template>

<script setup lang="ts">
import { getMyActivity, createActivityReceipt, cancelSignLog, getActivityQrcode, getCancelSignLinkManMobile, checkOrderStatus } from '@/api'
import { ref, defineAsyncComponent, computed, watch } from 'vue'
import { Dialog } from 'vant'
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex'
const NoData = defineAsyncComponent(() => import('@/components/NoData/index.vue'))
const router = useRouter()
const route = useRoute()
const store = useStore()
const loading: any = ref(false)
const showQrCode: any = ref(false)
const finished: any = ref(false)
const refreshing: any = ref(false)
const qrCodeUrl: any = ref('')
const activity: any = ref([
  {
    name: '我报名的'
  },
  {
    name: '我参与的'
  }
])
const form: any = ref({
  page: 1,
  pageSize: 10,
  get_type: route.query.s || 0
})

const phone: any = ref('')
const show: any = ref(false)

const demandList: any = ref([])

const selectedDemandTypeId = computed(() => {
  return Number(route.query.s) || 0
})

watch(selectedDemandTypeId, (newVal, oldVal) => {
  demandList.value = []
  onRefresh()
})

const checkItem = (index: any) => {
  form.value.get_type = index
  router.replace({
    path: '/userCenter/activities',
    query: { s: index }
  })
}

const back = () => {
  if (store.state.from.path !== '/') {
    router.back()
  } else {
    router.replace('/')
  }
}

const downPdf = (id: any, order_id:any) => {
  createActivityReceipt({
    activity_id: id,
    order_id: order_id
  }).then((res: any) => {
    console.log(res.receipt_url)
    window.location.href = res.receipt_url

    // const link = document.createElement('a')
    // link.setAttribute('href', res.receipt_url)
    // link.setAttribute('download', 'word.docx')
    // link.target = '_blank'
    // link.style.visibility = 'hidden'
    // document.body.appendChild(link)
    // link.click()
    // document.body.removeChild(link)
  })
}

const onRefresh = async () => {
  form.value.page = 1
  const list: any = await loadDemandList()
  demandList.value = list
  refreshing.value = false
}

const loadMore = async () => {
  form.value.page = form.value.page + 1
  const list: any = await loadDemandList()
  demandList.value = [...demandList.value, ...list]
  loading.value = false
}

const ActivityQrcode = async (id) => {
  // 报名成功打开二维码，提醒扫码加群
  getActivityQrcode({ activity_id: id }).then((res: any) => {
    if (res.url) {
      showQrCode.value = true
      qrCodeUrl.value = res.url
    } else {
      Dialog.alert({
        message: '暂无二维码',
        confirmButtonColor: '#FF7A1F'
      }).then(() => {
      })
    }
  })
}

const loadDemandList = async () => {
  // 异步更新数据
  const res: any =
    (await getMyActivity({ ...form.value, get_type: (Number(form.value.get_type) + 1) })) || []
  if (!Array.isArray(res) && typeof res.list === 'object') {
    const keys: any = Object.keys(res.list)
    const newRes: any = keys.map((k: any) => res.list[k])
    finished.value = newRes.length < form.value.pageSize
    return newRes
  }

  finished.value = res.list.length < form.value.pageSize
  return res
}

onRefresh()

const goActivity = async (id: any) => {
  router.push({ path: '/find/activity', query: { id: id } })
}

const cancellation = async (id: any, order_id:any) => {
  let type
  if (order_id) {
    type = await checkOrderStatus({ order_id: order_id })
  } else {
    type = { status: 1 }
  }
  console.log(type.status)
  if (!order_id && type.status === 1) {
    Dialog.confirm({
      title: '确认是否取消订单'
    }).then(() => {
      // on confirm
      cancelSignLog({ sign_id: id }).then((res: any) => {
        if (res) {
          Dialog.alert({
            message: '取消成功',
            confirmButtonColor: '#FF7A1F'
          }).then(() => {
            onRefresh()
          })
        }
      })
    }).catch(() => {
      // on cancel
    })
  } else if (order_id && type.status === 1) {
    Dialog.confirm({
      title: '确认是否取消订单'
    }).then(() => {
      // on confirm
      cancelSignLog({ sign_id: id }).then((res: any) => {
        if (res) {
          Dialog.alert({
            message: '取消成功',
            confirmButtonColor: '#FF7A1F'
          }).then(() => {
            onRefresh()
          })
        }
      })
    }).catch(() => {
      // on cancel
    })
  } else if (order_id && type.status !== 1) {
    phone.value = await getCancelSignLinkManMobile()
    console.log(phone.value)
    show.value = true
  }
}

</script>

<style lang="less" scoped>
.noBox {
  padding: 20px
}
.phone1 {
    text-align: center;
    a {
      color: #333;
    }
  }
.Scan {
  p {
    width: 190px;
    margin: 18px auto;
    text-align: center;
    line-height: 20px;
  }

  img {
    width: 120px;
    height: 120px;
    object-fit: contain;
    margin: 0 auto 20px auto;
  }
}
.confin {
    border-top: 1px solid #cacaca;
    .confinItem {
      flex: 1;
      text-align: center;
      height: 48px;
      line-height: 48px;
      border-right: 1px solid #cacaca;
    }
    .confinItemW {
      width: 100%;
    }
    .confinItem:last-child {
      border-right: 0;
    }
  }
.activeInfo {
  margin-bottom: 10px;
}
.copy {
  width: 68px;
  height: 25px;
  background: #12142e;
  border-radius: 5px;
  text-align: center;
  line-height: 25px;
}

.myactivities {
  padding: 0 15px 80px;
  margin-top: 40px;

  .myactivitiesBox {
    margin-top: 15px;
  }
}

.college_list {
  width: 100%;
  margin: 15px auto;
  background-color: #fff;
  border-radius: 5px;

  .college_list_box {
    display: flex;
    padding: 15px;

    .college_info {
      display: flex;
      flex-direction: column;
      justify-content: space-between;

      .radio {
        width: 10px;
        height: 10px;
        margin-right: 5px;
      }
    }

    .college_list_box_p {
      line-height: 20px;
    }

    // justify-content: space-between;
    .college_img {
      width: 100px;
      height: 70px;
      border-radius: 5px;
      object-fit: cover;
      margin-right: 14px;
    }

    .left12 {
      margin-left: 10px;
      color: #EE762A;
    }
  }
}

.square_header {
  .square_header_item {
    margin-right: 29px;
    text-align: center;

    .default {
      font-size: 19px;
      font-weight: bold;
      color: #454757;
    }
  }
}

.fexd_footer {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 70px;
  background-color: #fff;
  box-shadow: 0px 2px 12px 2px rgba(22, 12, 6, 0.09);

  .footer_btn {
    padding: 0 30px;
    height: 100%;
    text-align: center;

    .agree {
      width: 315px;
      height: 44px;
      background: #85898C;
      border-radius: 5px;
      text-align: center;
      line-height: 44px;
    }
  }
}

@media (min-width: 750px) {
  .myactivities {
    padding: 0 15px 80px;
    margin-top: 40px;

    .myactivitiesBox {
      margin-top: 15px;
    }
  }

  .college_list {
    width: 100%;
    margin: 15px auto;
    background-color: #fff;
    border-radius: 5px;

    .college_list_box {
      display: flex;
      padding: 15px;

      .college_info {
        display: flex;
        flex-direction: column;
        justify-content: space-between;

        .radio {
          width: 10px;
          height: 10px;
          margin-right: 5px;
        }
      }

      .college_list_box_p {
        line-height: 20px;
      }

      // justify-content: space-between;
      .college_img {
        width: 100px;
        height: 70px;
        border-radius: 5px;
        object-fit: cover;
        margin-right: 14px;
      }

      .left12 {
        margin-left: 10px;
        color: #EE762A;
      }
    }
  }

  .square_header {
    .square_header_item {
      margin-right: 29px;
      text-align: center;

      .default {
        font-size: 19px;
        font-weight: bold;
        color: #454757;
      }
    }
  }

  .fexd_footer {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 70px;
    background-color: #fff;
    box-shadow: 0px 2px 12px 2px rgba(22, 12, 6, 0.09);

    .footer_btn {
      padding: 0 30px;
      height: 100%;
      text-align: center;

      .agree {
        width: 315px;
        height: 44px;
        background: #85898C;
        border-radius: 5px;
        text-align: center;
        line-height: 44px;
      }
    }
  }
}
</style>
